package org.datastructure.firstday.search;

import java.util.ArrayList;
import java.util.List;

public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6};
//        System.out.println(binarySearch(arr, 7, 0, arr.length - 1));
        System.out.println(binarySearch1(arr, 0, arr.length - 1, 6));
    }

    public static int binarySearch(int[] arr, int val, int left, int right) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        if (arr[mid] < val) {
            return binarySearch(arr, val, mid + 1, right);
        } else if (arr[mid] > val) {
            return binarySearch(arr, val, left, mid - 1);
        } else {
            return mid;
        }
    }

    public static List<Integer> binarySearch1(int[] arr, int left, int right, int findVal) {
        if (left > right) return new ArrayList<Integer>();

        int mid = arr[(left + right) / 2];
        if (findVal > mid) {
            return binarySearch1(arr, mid + 1, right, findVal);
        } else if (findVal < mid) {
            return binarySearch1(arr, left, mid - 1, findVal);
        } else {
            List<Integer> elements = new ArrayList<>();
            int stemp = mid - 1;
            while (true) {
                if (stemp < 0 || arr[stemp] != findVal) {
                    break;
                }

                elements.add(stemp);
                stemp--;
            }
            elements.add(mid);
            stemp = mid + 1;
            while (true) {
                if (stemp > right || arr[stemp] != findVal) {
                    break;
                }
                elements.add(stemp);
                stemp++;
            }

            return elements;
        }
    }
}
